clear
discard
set more off

adopath ++ "./ado/"

******************
*** Parameters ***
******************

local file_name "./input/consensus_dataset.csv"  // Data file
local output_folder "./output/consensus" // Output directory
local K = 4 // Number of lags to include when calculating local projections
local L = 16 // Number of IRF coefficients to estimate
local alpha = 0.05 // Significance level
local L_NW = 5 // Number of lags for calculating Newey-West standard errors

*************************************
*** Import data and set data type ***
*************************************

import delimited using `file_name', case(preserve)
rename DATE Date

gen qtr = quarterly(Date,"YQ")
format qtr %tq
tsset qtr // Set to time series

********************************
*** Generate forecast errors ***
********************************

gen Efor_Step2 = Realiz1 - SPFfor_Step2

***********************************
*** Calculate local projections ***
***********************************

estimate_IRF_LP Realiz1, k(`K') l(`L') alpha(`alpha') min_lags_NW(`L_NW') 
matrix IRF_actual = e(s)

estimate_IRF_LP Efor_Step2, k(`K') l(`L') alpha(`alpha') min_lags_NW(`L_NW') 
matrix IRF_LP_1Q_ahead = e(s)

estimate_IRF_ML Efor_Step2, l(`L') alpha(`alpha')
matrix IRF_MA_1Q_ahead = e(s)

* Estimate a simple AR(4) for forecast errors
quietly newey Efor_Step2 l1.Efor_Step2 l2.Efor_Step2 l3.Efor_Step2 l4.Efor_Step2, lag(`K')
matrix AR_coefs = e(b)
matrix AR_coefs_cov = e(V)

******************
*** Get graphs ***
******************

* Clean up
shell rm -r `output_folder'
shell mkdir -p ./output
shell mkdir `output_folder'

* Get plots
plot_IRF "IRF_actual" `output_folder' "IRF_actual"
plot_IRF "IRF_LP_1Q_ahead" `output_folder' "IRF_LP_1Q_ahead"
plot_IRF "IRF_MA_1Q_ahead" `output_folder' "IRF_MA_1Q_ahead"

* Save estimated IRFs
mat2txt, matrix(IRF_actual) saving(`output_folder'/IRF_actual.txt)
mat2txt, matrix(IRF_LP_1Q_ahead) saving(`output_folder'/IRF_LP_1Q_ahead.txt)
mat2txt, matrix(IRF_MA_1Q_ahead) saving(`output_folder'/IRF_MA_1Q_ahead.txt)
mat2txt, matrix(AR_coefs) saving(`output_folder'/AR_coefs_1Q_ahead.txt)
mat2txt, matrix(AR_coefs_cov) saving(`output_folder'/AR_coefs_cov_1Q_ahead.txt)

* Get summary statistics
summary_stats_forecasts Efor_Step2 Realiz1, k(`K')
matrix stats_Step2 = e(s)
mat2txt, matrix(stats_Step2) saving(`output_folder'/stats_1Q_ahead.txt)
